package com.stars.controller.sys;


import com.stars.common.annotation.UserMenuUpdateRedis;
import com.stars.common.base.BaseCode;
import com.stars.common.base.ResultMsg;
import com.stars.common.result.JSRResult;
import com.stars.controller.advice.CommonExceptionHandler;
import com.stars.entity.sys.SystemUserRelation;
import com.stars.services.system.UserRelationAccessService;
import com.stars.services.system.UserRelationConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author : dj
 * @version ：1.0.0
 * @Date : create by 2018/12/5 11:13
 * @description ：角色和用户关系控制层
 * @note 注意事项
 */
@RestController
@RequestMapping(value = "/userRelation")
@Api(tags = "角色和用户关系控制层")
public class UserRelationController extends CommonExceptionHandler {

    @Autowired
    private UserRelationConfigService userRelationConfigServiceImpl;
    @Autowired
    private UserRelationAccessService userRelationAccessServiceImpl;

    /**
     * 添加角色和用户的关系
     * @param userRelation
     * @param bindingResult
     * @return
     * @throws Exception
     */
   @PostMapping(value = "/userRelationInsert")
   @ApiOperation(value = "添加角色和用户的关系")
   @UserMenuUpdateRedis(permission = true)
   public ResultMsg userRelationInsert(@Valid SystemUserRelation userRelation, BindingResult bindingResult) throws Exception{
       String messageString = JSRResult.hasError(bindingResult);
       if(!BaseCode.SUCCESS.equals(messageString)){
           return ResultMsg.failure(messageString);
       }

       SystemUserRelation byRelationIdAndRoleId = userRelationAccessServiceImpl.findByRelationIdAndRoleId(userRelation);
       if(null!=byRelationIdAndRoleId){
           return ResultMsg.failure("该关系已经存在，请勿重复添加!");
       }
       userRelationConfigServiceImpl.userRelationInsert(userRelation);
       return ResultMsg.success();
   }

    /**
     * 修改用户和角色关系
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateRelation")
    @ApiOperation(value = "修改用户和角色关系")
    @UserMenuUpdateRedis(permission = true)
    public ResultMsg updateRelation(@RequestBody Map<String, Object> map) throws Exception{
        return userRelationConfigServiceImpl.updateRoleAndUser(map);
    }

}
